#include "media/logic/MediaLogicTT.h"


MediaLogicTT::MediaLogicTT(QMap<QString, QMap<QString, QString>> &RGLRLSMAP,
                           QSqlDatabase *DB,
                           QMap<QString, QString> &QSSMAP)
    : MediaWin(RGLRLSMAP, DB, QSSMAP){

}

void MediaLogicTT::abstract_loader_processing(double process, QString name){
    if (RT_sliderShow->currentWidget() != LD_chedulewin)
    {
        RT_sliderShow->setCurrentWidget(LD_chedulewin);
        diary("running loading prograss view mdl", Diary::Warning);
    }
    if (static_cast<int>(ceil(process)) == 100) RT_sliderShow->backview();
    LD_cheduleBar->setValue(process, name);
}

void MediaLogicTT::abstract_reserve_loader(QString fillersql){
    NT::CUT_MEDIA_TYPE mediaSwitch = static_cast<NT::CUT_MEDIA_TYPE>(impact_identify["mdrs-table-type"]);
    if (!MT_MediaPlayer->hasVideo())
    {
        if (mediaSwitch == NT::CUT_MUSIC_TYPE)
        {
            emit sg_fromtype_amend(NT::CUT_MUSIC_TYPE, fillersql);
        }
        else if (mediaSwitch == NT::CUT_VIDEO_TYPE)
        {
            emit sg_fromtype_amend(NT::CUT_VIDEO_TYPE, fillersql);
        }
    }
    diary2("auto loader according type: ",mediaSwitch, Diary::Warning)
}

void MediaLogicTT::system_willbe_quit(){
    MessageBoxQ *HintMessage = new MessageBoxQ(this,
                                               {"Exit", "Ignore"},
                                               MessageBoxQ::MSG_Question,
                                               "Question",
                                               "Are You To Be Exit?");
    QObject::connect(HintMessage, &MessageBoxQ::checkEvent, this, &MediaLogicTT::system_quit_carryout);
}

void MediaLogicTT::system_quit_carryout(QAbstractButton *button){
    if (button->text() == "Exit")
    {
        BoilPool->clear();
        setWindowOpacity(0);
        captionBar()->setWindowOpacity(0);
        if (NW_blackBoard->isVisible()) NW_blackBoard->close();
        if (RT_videoWidget->isVisible()) RT_videoWidget->close();
        /* -----------------THREAD--QUIT---------------------*/
        thread_state_assert(ThreadPoint::MULTI_MDCVUPDATE);
        thread_state_assert(ThreadPoint::MULTI_NWRQST);
        thread_state_assert(ThreadPoint::MULTI_TABUPDATE);
        thread_state_assert(ThreadPoint::NETWORK_VISIT);
        thread_state_assert(ThreadPoint::MULTI_ADDTION);
        thread_state_assert(ThreadPoint::MULTI_REMOVE);
        connect(&GLOBAL_SYSTEM_QUIT_QTIER, &QTimer::timeout, this, [&](){
            bool MULTI_MDCVUPDATE = (impact_thread[ThreadPoint::MULTI_MDCVUPDATE] == NT::THREAD_IDLEABOUT);
            bool MULTI_NWRQST = (impact_thread[ThreadPoint::MULTI_NWRQST] == NT::THREAD_IDLEABOUT);
            bool MULTI_TABUPDATE = (impact_thread[ThreadPoint::MULTI_TABUPDATE] == NT::THREAD_IDLEABOUT);
            bool NETWORK_VISIT = (impact_thread[ThreadPoint::NETWORK_VISIT] == NT::THREAD_IDLEABOUT);
            bool MULTI_REMOVE = (impact_thread[ThreadPoint::MULTI_REMOVE] == NT::THREAD_IDLEABOUT);
            bool MULTI_ADDTION = (impact_thread[ThreadPoint::MULTI_ADDTION] == NT::THREAD_IDLEABOUT);
            bool MULTI_AMEND = (impact_thread[ThreadPoint::MULTI_AMEND] == NT::THREAD_IDLEABOUT);
            if (MULTI_MDCVUPDATE && MULTI_NWRQST && MULTI_TABUPDATE && NETWORK_VISIT && MULTI_REMOVE && MULTI_ADDTION && MULTI_AMEND)
            {
                emit sg_system_quit(true, NT::WIN_QUIT_ATTRIBUTE::CHILD_MEDIA_QUIT);
                impact_swtc["user-accept-might"] ? emit sg_userinfo_quit() : close();
                impact_int["tsseac"] = 0;
                GLOBAL_SYSTEM_QUIT_QTIER.stop();
            }
            else
            {
                if (impact_int["tsseac"] == 30)
                {
                    diary6("MULTI_MDCVUPDATE: ", MULTI_MDCVUPDATE, " MULTI_NWRQST: ", MULTI_NWRQST, " MULTI_TABUPDATE: ", MULTI_TABUPDATE, Diary::Warning)
                    diary6("NETWORK_VISIT: ", NETWORK_VISIT, " MULTI_REMOVE: ", MULTI_REMOVE, " MULTI_ADDTION: ", MULTI_ADDTION, Diary::Warning)
                    diary2("MULTI_AMEND: ", MULTI_AMEND, Diary::Warning)
                }
            }
            impact_int["tsseac"] += 1;
        });
        GLOBAL_SYSTEM_QUIT_QTIER.start();
        /* -----------------THREAD--QUIT---------------------*/
    }
}

bool MediaLogicTT::nativeEvent(const QByteArray &eventType, void *message, qintptr *result)
{
    MSG *winsuerMsg = (MSG *)message;
    if (winsuerMsg->message == WM_CLOSE)
    {
        system_willbe_quit();
        return true;
    }
    return QWidget::nativeEvent(eventType, message, result);
}

void MediaLogicTT::network_searchinfo(unsigned int way){
    QString match_text = NW_matchComboBox->g_linedit()->text();
    if (way == SEARCHFUNC_INIT)
    {
        if (!match_text.isEmpty())
        {
            QRegularExpression splitinfo("[&|\\s+|-|=]");
            impact_ststr["search-detail-info"] = match_text.split(splitinfo);
            if (impact_swtc["search-state"]) impact_thread[ThreadPoint::MULTI_NWRQST] = NT::THREAD_TERMINATED;
            bool unequal = (impact_ststr["search-detail-info"] != impact_ststr["search-detail-auldinfo"]);
            if (unequal)
            {
                impact_thread[ThreadPoint::MULTI_NWRQST] = NT::THREAD_RECOVER;
                NW_blackBoard->priview()->clearContents();
                network_searchexec();
            }
            else
            {
                RT_sliderShow->setCurrentWidget(NW_blackBoard);
                NW_blackBoard->activateWindow();
                LF_localMeidaLabel->doconfigur_unlock();
                LF_nearMeidaLabel->doconfigur_unlock();
                LF_recordLabel->doconfigur_unlock();
                Favora_ListWidget->unselected();
                NW_matchComboBox->g_stall()->addItem(match_text);
            }
        }
    }

    else if (way == SEARCHFUNC_TRYLST || way == SEARCHFUNC_DLMDRS)
    {
        QList<int> selects = NW_blackBoard->priview()->prossRows();
        for(int slsrow : selects)
        {
            QString url = impact_ststr["network-visit-resource-urls"][slsrow];
            QString mdrs_path = impact_ststr["network-visit-resource-paths"][slsrow];
            QString mdrs_name = QFileInfo(mdrs_path).baseName().split("-").first();
            QString mdrs_artist = QFileInfo(mdrs_path).baseName().split("-").last();
            QString mdrs_suffix = QFileInfo(mdrs_path).suffix();
            QString mdrs_df_owner = impact_str["mdrs-owner"];
            QString mdrs_prdtime = QDateTime().currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
            QString mdrs_curtime = QDateTime().currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
            if (way == SEARCHFUNC_TRYLST)
            {
                QList<QString> mdrs_cols({"mdrs_name", "mdrs_artist", "mdrs_path", "mdrs_suffix", "mdrs_size", "mdrs_duration", "mdrs_bitrate",
                                          "mdrs_state", "prd_time", "alter_time", "mdrs_lyric", "owner"});
                QList<QString> mdrs_values({mdrs_name, mdrs_artist, url, mdrs_suffix, "", "", "",
                                            QString::number(false), mdrs_prdtime, mdrs_curtime, "", mdrs_df_owner});
                if (impact_ststr["fm-ovall"].contains(mdrs_suffix))
                {
                    if (impact_ststr["anysql-name"].contains(mdrs_name))
                    {
                        QStringList sqlupcharli;
                        for(int i = 0; i < mdrs_cols.size(); i++)
                        {
                            sqlupcharli.append(mdrs_cols[i] + '=' + "'" + mdrs_values[i] + "'");
                        }
                        Query->exec(QString("UPDATE media_datum SET (%1) WHERE mdrs_name = '%2';").arg(sqlupcharli.join(","), mdrs_name));
                    }
                    else
                    {
                        Query->exec(QString("INSERT INTO media_datum(%1) values(%2);").arg(mdrs_cols.join(","), definfc.join(mdrs_values, "'%1'", ",")));
                    }
                }
                emit sg_alldata_query();
            }
            else if (way == SEARCHFUNC_DLMDRS)
            {
                QList<QVariant> receiveli;
                SCROPED_RESDOWN_SINGEXEC(url, NULL, mdrs_path, FLAG_RESHOURCE_GET, QDateTime::currentDateTime().toString(), receiveli, impact_thread);
                impact_ststr["mdrs-local-files"].append(mdrs_path);
                BoilPool->run(ThreadPoint::MULTI_ADDTION);
            }

        }
    }

    else if (way == SEARCHFUNC_VIEWBACK)
    {
        RT_sliderShow->backview();
    }
}

void MediaLogicTT::network_searchexec(){
    QList<QVariant> requestli;
    QList<QVariant> receiveli;
    QList<QString> multi_search_infos = impact_ststr["search-detail-info"];
    QString visitRangeChar = (*__RLMAP__)["MSC"]["NetworkVisitRangeNum"];
    int visitRange;
    Extend::isInt(visitRangeChar) ? visitRange = visitRangeChar.toInt() : visitRange = 10;
    foreach(QString search, multi_search_infos) requestli.append(REGISTER_BASEINFO_163MSC_ADDRESS.arg(search, QString::number(visitRange)));
    diary("search info count: " + QString::number(requestli.length()), Diary::Debug)
    QString key = QDateTime::currentDateTime().toString(Qt::DateFormat::TextDate);
    SCROPED_RESDOWN_ROPEEXEC(requestli, NULL, NULL, FLAG_RESHOURCE_GET, key, receiveli, impact_thread)
    diary4("request count: ", QString::number(requestli.size()), " receive info count: ", QString::number(receiveli.size()), Diary::Debug)
    if (!receiveli.isEmpty())
    {
        impact_swtc["search-state"] = true;
        NW_blackBoard->priview()->setRowCount(visitRange);
        for(int row = 0; row < visitRange; row++) NW_blackBoard->priview()->setRowHeight(row, 80);
        if (RT_sliderShow->currentWidget() != NW_blackBoard)
        {
            RT_sliderShow->setCurrentWidget(NW_blackBoard);
        }
    }
    int global_index = 0;
    while (global_index < receiveli.size())
    {
        QVariant receiveinfo = receiveli[global_index];
        if (impact_thread[ThreadPoint::MULTI_NWRQST] == NT::THREAD_TERMINATED)
        {
            break;
        }
        else if (impact_thread[ThreadPoint::MULTI_NWRQST] == NT::THREAD_PAUSE)
        {
            while (true)
            {
                if (impact_thread[ThreadPoint::MULTI_NWRQST] == NT::THREAD_PAUSE)
                {
                    QThread::msleep(15);
                    continue;
                }
                else
                {
                    break;
                }
            }
        }
        else
        {
            QJsonDocument infodocument = ResdownLoad::jsparser(receiveinfo.toByteArray());
            ResdownLoad::mdpldata infostruct = ResdownLoad::jsparserTostruct(infodocument, STRUCTYPE_MDRS);
            if (!infostruct.MDRS_ID.isEmpty())
            {
                QList<QString> savepaths;
                for(int indexx = 0; indexx <infostruct.MDRS_ID.size(); indexx++)
                {
                    QList<QString> songsinfo = infostruct.get(indexx);
                    QVariant pixVariant;
                    QString simplename = songsinfo[1] + "-" + songsinfo[2];
                    QString savepath = (*__RLMAP__)["PATH"]["MSPATH"] + "/" + simplename + "." + "mp3";
                    if (songsinfo.size() >= 4)
                    {
                        QList<QVariant> coverli;
                        diary(REGISTER_INFODETAIL_163MSC_ADDRESS.arg(songsinfo[0]), Diary::Debug)
                        SCROPED_RESDOWN_SINGEXEC(REGISTER_INFODETAIL_163MSC_ADDRESS.arg(songsinfo[0]), NULL, NULL, FLAG_RESHOURCE_GET, key, coverli, impact_thread)
                        foreach(QVariant cover, coverli)
                        {
                            QJsonDocument coverdocument = ResdownLoad::jsparser(cover.toByteArray());
                            if (coverdocument["songs"].type() == QJsonValue::Array && coverdocument["songs"].toArray().size() >= 1)
                            {
                                QJsonObject album = coverdocument["songs"].toArray()[0].toObject();
                                QJsonValue album_pic = album["album"].toObject()["picUrl"];
                                QJsonValue album_name = album["album"].toObject()["name"];
                                songsinfo[3] = album_pic.toString();
                                songsinfo[4] = album_name.toString();

                            }
                            SCROPED_RESDOWN_SINGEXEC(songsinfo[3], NULL, NULL, FLAG_RESHOURCE_GET, key, pixVariant, impact_thread)
                            QPixmap pixmap;
                            if (!pixmap.loadFromData(pixVariant.toByteArray()))
                            {
                                pixmap.load(":/PIXMAP/bench/cover.jpg");
                            }
                            NW_blackBoard->nw_viewlayout_init(indexx, songsinfo[1] , songsinfo[2], songsinfo[4], pixmap);
                            captionBar()->setFocus();
                            diary("base info send", Diary::Debug);
                        }
                    }
                    savepaths.append(savepath);
                }
                impact_ststr["network-visit-resource-urls"] = infostruct.MDRS_URL;
                impact_ststr["network-visit-resource-paths"] = savepaths;
            }
            break;
        }
        global_index++;
    }
    impact_thread[ThreadPoint::MULTI_NWRQST] = NT::THREAD_IDLEABOUT;
    impact_swtc["search-state"] = false;
    impact_ststr["search-detail-auldinfo"] = multi_search_infos;
    impact_thread[ThreadPoint::MULTI_NWRQST] = NT::THREAD_IDLEABOUT;
}
